package cn.bincker.audiostream;

import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

@Controller
@RequestMapping
public class IndexController {
    @GetMapping
    public String index(){
        return "index";
    }

    @GetMapping("music-stream")
    public void musicStream(HttpServletResponse response){
        response.addHeader(HttpHeaders.CONTENT_TYPE, "audio/mpeg;charset=UTF-8");
        try(
                InputStream in = new FileInputStream(ResourceUtils.getFile("classpath:static/music1.mp3"));
                OutputStream out = response.getOutputStream()
        ) {
            byte[] bytes = new byte[8192];
            int len;
            while ((len = in.read(bytes)) > 0) out.write(bytes, 0, len);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
